// src/pages/PermissionList/components/PermissionModal.tsx
import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, InputNumber, message } from 'antd';
import {
    getPermissionInfo,
    addPermission,
    editPermission,
} from '@/services/permission';

const { Option } = Select;

type PermissionModalProps = {
    visible: boolean;
    isEdit: boolean;
    disableSubmit: boolean;
    currentPermission?: any;
    currentPermissionId: number;
    addParentPermissionId: number;
    onOk: (values: any) => void;
    onCancel: () => void;
};

const PermissionModal: React.FC<PermissionModalProps> = ({
                                                             visible,
                                                             isEdit,
                                                             disableSubmit,
                                                             currentPermission,
                                                             currentPermissionId,
                                                             addParentPermissionId,
                                                             onOk,
                                                             onCancel,
                                                         }) => {
    const [form] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);

    useEffect(() => {
        if (visible && currentPermissionId && isEdit) {
            // 编辑时加载权限详情
            loadPermissionData(currentPermissionId);
        } else if (visible && !isEdit) {
            // 新增时重置表单
            form.resetFields();
            if (addParentPermissionId){
                form.setFieldsValue({parentId: addParentPermissionId});
            }
        }
    }, [visible, currentPermissionId, isEdit, form]);

    const loadPermissionData = async (id: number) => {
        try {
            const response = await getPermissionInfo({id});
            if (response.code == 200) {
                form.setFieldsValue(response.data);
            } else {
                message.error(response.message || '获取权限信息失败');
            }
        } catch (error) {
            console.error('加载权限信息失败:', error);
            message.error('获取权限信息失败');
        }

        // try {
        //     const response = await getPermissionMenu();
        //     // Mock API 返回格式为 { success: boolean, message: string, result: { records: PermissionItem[], total: number } }
        //     if (response.code === 200) {
        //         return {
        //             // --- 修正：使用  键 ---
        //             data: response.data?.list || [],
        //             success: true,
        //             total: response.data?.totalCount || 0,
        //         };
        //     } else {
        //         message.error(response.message || '获取数据失败');
        //         return {
        //             // --- 修正：使用  键 ---
        //             data: [],
        //             success: false,
        //             total: 0,
        //         };
        //     }
        // } catch (error: any) {
        //     console.error('获取权限列表失败:', error);
        //     message.error(error?.message || '获取数据失败');
        //     return {
        //         // --- 修正：使用  键 ---
        //         data: [],
        //         success: false,
        //         total: 0,
        //     };
        // }
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            setConfirmLoading(true);

            let response;
            if (isEdit && currentPermissionId) {
                // 编辑
                response = await editPermission({ ...values, id: currentPermissionId });
            } else {
                // 新增
                response = await addPermission(values);
            }

            if (response.success) {
                message.success(response.message || (isEdit ? '编辑成功' : '新增成功'));
                onOk(values);
            } else {
                message.error(response.message || (isEdit ? '编辑失败' : '新增失败'));
            }
        } catch (error) {
            console.error('提交表单失败:', error);
        } finally {
            setConfirmLoading(false);
        }
    };

    return (
        <Modal
            title={isEdit ? '编辑权限' : '新增权限'}
            open={visible}
            onOk={handleOk}
            onCancel={onCancel}
            confirmLoading={confirmLoading}
            maskClosable={false}
            width={600}
        >
            <Form
                form={form}
                layout="vertical"
                disabled={disableSubmit}
            >
                <Form.Item
                    name="parentId"
                    label="父级权限"
                    rules={[{ required: true, message: '请输入权限名称!' }]}
                >
                    <Input placeholder="请输入权限名称" />
                </Form.Item>
                <Form.Item
                    name="name"
                    label="权限名称"
                    rules={[{ required: true, message: '请输入权限名称!' }]}
                >
                    <Input placeholder="请输入权限名称" />
                </Form.Item>
                <Form.Item
                    name="code"
                    label="权限编码"
                    rules={[
                        { required: true, message: '请输入权限编码!' },
                    ]}
                >
                    <Input placeholder="请输入权限编码" disabled={isEdit} />
                </Form.Item>
                <Form.Item
                    name="type"
                    label="菜单类型"
                    rules={[{ required: true, message: '请选择菜单类型!' }]}
                >
                    <Select placeholder="请选择菜单类型">
                        <Option value={0}>目录</Option>
                        <Option value={1}>菜单</Option>
                        <Option value={2}>按钮/权限</Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="path"
                    label="菜单路径"
                >
                    <Input placeholder="请输入菜单路径" />
                </Form.Item>
                {/*TODO 初期靠手动填写*/}
                <Form.Item
                    name="icon"
                    label="菜单图标"
                >
                    <Input placeholder="请输入菜单图标" />
                </Form.Item>
                <Form.Item
                    name="component"
                    label="前端组件"
                >
                    <Input placeholder="请输入前端组件" />
                </Form.Item>
                <Form.Item
                    name="sortNo"
                    label="排序"
                >
                    <InputNumber placeholder="请输入排序号" style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item
                    name="description"
                    label="描述"
                >
                    <Input.TextArea placeholder="请输入描述" rows={4} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default PermissionModal;